<!--选择页（设备）-->
<template>
	<view class="select-main">
		<nav-bar class="header" back :title="title" @goBack="goBack">
			<slot slot="iconfont" name="headAdd"></slot>
		</nav-bar>
		<view class="main-container">
			<!-- 搜索框  -->
			<view class="search">
				<van-search disabled v-model="searchValue" left-icon="" right-icon="search"
					:placeholder="equObj.isCheckbox?'请输入设备名称':'请输入站点名称'" @click="showSearch = true;" />
			</view>

			<!-- 选项列表 -->
			<view class="option-list-with-sub">
				<!--        -->
				<ly-tree :tree-data="treeData" :showCheckbox="equObj.isCheckbox" :showRadio="!equObj.isCheckbox"
					:props="props" :ready="ready" node-key="ORGID" @check="handleCheck" @node-expand="handleNodeExpand"
					@node-click="handleNodeClick" ref="tree">
				</ly-tree>
			</view>

		</view>
		<view class="bottom-container">
			<view class="select-result" @click="resultShow= true">
				<view class="sel_res_lf">
					<view v-if="resList.length>0">
						已选择：{{resList.length+'个'}}
						<van-icon name="arrow-up" />
					</view>
					<view class="sel_res_text" v-if="resList.length>0">{{resList[0].NAME}}</view>
				</view>
			</view>
			<text v-if="resList.length>0" class="clr-btn" @click="clear">清空</text>
			<van-button color="#417ADC" @click="confirm()">确定</van-button>
		</view>
		<van-action-sheet v-model="resultShow">
			<van-cell :title="`已选择${resList.length}人`">
				<template #right-icon>
					<van-button round type="info" size="mini" style="width:px2vw(40)" @click="resultShow= false">确 认
					</van-button>
				</template>
			</van-cell>
			<van-list v-model="resLoading" :finished="resFinished" @load="resOnLoad" class="list-wrap">
				<van-cell :title="item.NAME" v-for="(item,index) in resList" :key="index">
					<template #right-icon>
						<view @click="handleReomve(index)">移除</view>
					</template>
				</van-cell>
			</van-list>
		</van-action-sheet>
		<!--弹出搜索页-->
		<van-popup v-model="showSearch" position="right">
			<search @cancel="showSearch = false;" @search="onSearch" :empty="showSearch" />
		</van-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapGetters,
		mapActions,
		mapMutations
	} from 'vuex'
	import navBar from '../../../components/common/nav-bar'
	import search from './search'
	import LyTree from '@/components/ly-tree/ly-tree.vue'
	export default {
		name: 'selectEquipment',
		components: {
			navBar,
			LyTree,
			search
		},
		computed: {
			...mapGetters(['userData'])
		},
		props: {
			selected: {
				type: [Object, Array]
			},
			equObj: {
				type: Object,
				default () {
					return {
						equType: 'equipment',
						siteId: '',
						batchId: '',
						isCheckbox: false
					}
				}
			}
		},
		watch: {
			selected: {
				handler: function(newVal) {
					this.$nextTick(() => {
						if (Array.isArray(newVal)) {
							if (newVal && newVal.length > 0) {
								let arr = []
								newVal.forEach(item => {
									arr.push(item.ORGID)
								})
								this.$refs.tree.setCheckedKeys(arr)
								this.resList = newVal
							} else {
								this.$refs.tree.setCheckedNodes([])
								this.resList = []
							}
						} else {
							// object 单选
							if (newVal && newVal.ORGID) {
								this.$refs.tree.setCheckedKeys([newVal.ORGID])
								this.resList = [newVal]
							} else {
								this.$refs.tree.setCheckedKeys([])
								this.resList = []
							}
						}
					})
				},
				immediate: true,
				deep: true
			},
			equObj: {
				handler: function(newVal) {
					console.log("newVal", newVal)
					this.resList = []
					this.siteId = newVal.siteId
					this.batchId = newVal.batchId
					if (this.siteId) {
						this.props.canAllSelect = true
					}
					this.searchValue = ''
					if (newVal.equType == 'equipment') {
						this.props.selectKey = 'SITEID'
						this.title = '选择通信设备'
						this.selectDtAppEquipmentList() // 选择通信设备
					} else if (newVal.equType == 'powerSupply') {
						this.props.selectKey = 'SITEID'
						this.title = '选择通信电源设备'
						this.selectDtAppEquipmentPowerList() // 选择电源设备
					} else {
						this.props.selectKey = 'A_RESOBJID'
						this.title = '选择通信光缆设备'
						this.selectOpticalList() // 选择光缆设备
					}
				},
				immediate: true,
				deep: true
			},
			// resList: {
			//   handler: function () {},
			//   immediate: true,
			//   deep: true
			// }
		},
		data() {
			return {
				ready: false, // 这里用于自主控制loading加载状态，避免异步正在加载数据的空档显示“暂无数据”
				treeData: [],
				props: {
					label: 'NAME', // 指把数据中的‘personName’当做label也就是节点名称
					children: 'siteList', // 指把数据中的‘childs’当做children当做子节点数据
					selectKey: '', // 自定义参数--根据参数判断数据节点是否可进行勾选
					canAllSelect: false, // 自定义参数--多选情况下，是否可以全选（放开父级节点checked）
					disabled: (data, node) => {
						return data.TOUR_STATE == '1'
					}
				},
				resultShow: false,
				title: '选择设备',
				showSearch: false,
				searchValue: '',
				siteId: '',
				batchId: '',

				resLoading: false,
				resFinished: false,
				resList: []
			}
		},
		mounted() {},
		methods: {
			goBack() {
				this.$emit('cancel')
			},
			confirm() {
				if (this.equObj.isCheckbox) {
					// 多选
					this.$emit('changeSelected', this.resList)
				} else {
					// 单选
					this.$emit('changeSelected', this.resList.length === 0 ? {
						NAME: '',
						ORGID: '',
						SITEID: ''
					} : this.resList[0])

				}

				this.$emit('cancel')
			},
			handleReomve(i) {
				this.resList.splice(i, 1)
			},
			clear() {
				this.$refs.tree.setCheckedKeys([])
				// this.$emit('update:selected', {
				//   NAME: '',
				//   ORGID: '',
				//   SITEID: ''
				// })
				this.resList = []
			},
			onSearch(searchValue) {
				this.$emit('update:selected', {
					ORGID: '',
					NAME: '',
					SITEID: ''
				})
				this.searchValue = searchValue
				var params = {}
				if (this.equObj.isCheckbox) {
					// 多选
					params = {
						objId: this.siteId,
						batchId: this.batchId,
						name: this.searchValue
					}
				} else {
					// 单选
					if (this.searchValue) {
						params = {
							objId: '',
							batchId: this.batchId,
							// name: this.searchValue,
							orgId: this.userData.orgId,
							siteName: this.searchValue
						}
					} else {
						params = {
							objId: this.siteId,
							batchId: this.batchId,
							name: this.searchValue
						}
					}
				}
				if (this.equObj.equType == 'equipment') {
					this.selectDtAppEquipmentList(params) // 选择通信设备
				} else if (this.equObj.equType == 'powerSupply') {
					this.selectDtAppEquipmentPowerList(params) // 选择电源设备
				} else {
					this.selectOpticalList(params) // 选择光缆设备
				}
				this.showSearch = false

				// this.searchValue
			},

			// uni-app中emit触发的方法只能接受一个参数，所以会回传一个对象，打印对象即可见到其中的内容
			handleNodeClick(obj) {
				console.log('handleNodeClick', JSON.stringify(obj))
			},
			handleNodeExpand(obj) {
				console.log('handleNodeExpand', JSON.stringify(obj))
			},
			handleCheck(obj) {
				if (this.equObj.isCheckbox) {
					// 多选
					let nodes = []
					obj.checkedNodes.map(item => {
						if (item[this.props.selectKey]) {
							nodes.push({
								ORGID: item.ORGID,
								NAME: item.NAME,
								SITEID: item.SITEID
							})
						}
					})
					// if (obj.node.checked) {
					//   this.$emit('update:selected', nodes)
					// } else {
					//   this.$emit('update:selected', nodes)
					// }
					this.resList = nodes
				} else {
					// 单选
					if (obj.node.checked) {
						this.$emit('update:selected', {
							ORGID: obj.data.ORGID,
							NAME: obj.data.NAME,
							SITEID: obj.data.SITEID
						})
					} else {
						this.$emit('update:selected', {
							ORGID: '',
							NAME: '',
							SITEID: '',
						})
					}
					this.resList = [{
						ORGID: obj.data.ORGID,
						NAME: obj.data.NAME,
						SITEID: obj.data.SITEID
					}]
				}
			},
			resOnLoad() {
				setTimeout(() => {
					// for (let i = 0; i < 4; i++) {
					//   this.resList.push({ name: '张三' + i })
					// }
					// 加载状态结束
					this.resLoading = false
					// 数据全部加载完成
					this.resFinished = true
				}, 100)
			},
			async selectDtAppEquipmentList(obj) {
				let params = obj ?
					obj : {
						objId: this.siteId,
						batchId: this.batchId,
						name: this.searchValue
					}
				await this.$apiRequest.bzhzyApi.selectDtAppEquipmentList(params).then(res => {
					this.treeData = res.data.siteList
					this.ready = true
				})
			},
			async selectDtAppEquipmentPowerList(obj) {
				let params = obj ?
					obj : {
						objId: this.siteId,
						batchId: this.batchId,
						name: this.searchValue
					}
				await this.$apiRequest.bzhzyApi.selectDtAppEquipmentPowerList(params).then(res => {
					this.treeData = res.data.siteList
					this.ready = true
				})
			},
			async selectOpticalList(obj) {
				let params = obj ?
					obj : {
						objId: this.siteId,
						batchId: this.batchId,
						name: this.searchValue
					}
				await this.$apiRequest.bzhzyApi.selectOpticalList(params).then(res => {
					this.treeData = res.data.siteList
					// this.deep(res.data.siteList)
					this.ready = true
				})
			},
			deep(siteList) {
				siteList.forEach(element => {
					if (element.ORGID === '153' || element.ORGID === '154') {
						console.log(element)
					}

					if (element.siteList) {
						this.deep(element.siteList)
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.select-main {
		height: 100vh;
		background-color: #f8f8f8;
		font-family: vant-icon;

		.header {
			position: sticky;
			top: 0;
			z-index: 9;

			img {
				width: px2vw(48);
				margin-right: px2vw(40);
			}
		}

		.main-container {
			min-height: calc(100vh - #{px2vh(363)});
			padding: px2vh(30) px2vw(30) px2vh(30) px2vw(30);

			.search {
				width: px2vw(1020);
				height: px2vh(110);
				margin: auto auto px2vh(50);
				border-radius: $border-radius-base;
				overflow: hidden;

				.van-search {
					padding: 0;
					height: px2vh(110);

					.van-search__content {
						background: #fff;
						height: 38px;
					}
				}

				/deep/.van-field__control {
					height: 30px;
				}
			}
		}

		.bottom-container {
			display: flex;
			width: 91vw;
			justify-content: space-between;
			align-items: center;
			z-index: 99;
			position: sticky;
			bottom: 0;
			height: px2vh(100);
			padding: px2vh(20) px2vw(40) px2vh(20) px2vw(49);
			background-color: #fff;

			.select-result {
				width: calc(100% - #{px2vw(240)} - #{px2vw(67)});
				// background: #acf;
				display: flex;
				align-items: center;
				justify-content: flex-start;

				.sel_res_lf {
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					justify-content: center;
					color: #417adc;
				}

				.sel_res_text {
					max-width: px2vw(530);
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}

			.clr-btn {
				color: #ee0a24;
				width: px2vw(120);
			}

			.van-button {
				height: px2vh(100);
				width: px2vw(240);
				font-size: px2vh(42);
				border-radius: px2vh(20);
			}
		}

		.option-list-with-sub {
			width: px2vw(1020);
			height: px2vh(1360);
			overflow-y: auto;
		}
	}

	.list-wrap {
		height: px2vh(600);
		margin-bottom: px2vh(20);
		overflow-y: auto;
	}
</style>
